/*
 * Copyright 2010 Askar Kalykov, oxygene.core@gmail.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.oxygenecore.processor.expression.arithmetic.integer;

import com.oxygenecore.processor.CalculationException;
import com.oxygenecore.processor.ExecutionContext;
import com.oxygenecore.processor.Expression;
import com.oxygenecore.processor.UnsupportedExpressionException;
import com.oxygenecore.processor.expression.arithmetic.ArithmeticExpression;

/**
 * @author Askar Kalykov
 *         Date: 11.09.2010
 *         Time: 18:25:31
 */
abstract public class AbstractIntegerArithmeticExpression implements ArithmeticExpression<Integer> {
    private Expression<Integer>[] parameters;
    private Operation operation;

    protected AbstractIntegerArithmeticExpression(Operation operation, Expression<Integer> ... parameters) {
        if (operation == null){
            throw new NullPointerException("operation");
        }
        for (Expression<Integer> parameter : parameters) {
            if (parameter == null){
                throw new NullPointerException("one of parameters is null");
            }
        }
        this.operation = operation;
        this.parameters = parameters;
    }

    public Integer getValue(ExecutionContext executionContext) throws CalculationException {
        switch (operation){
            case ADD: {
                int summ = 0;
                for (Expression<Integer> parameter : parameters) {
                    summ += parameter.getValue(executionContext);
                }
                return summ;
            }
            case DIVIDE: {
                return parameters[0].getValue(executionContext)/parameters[1].getValue(executionContext);
            }
            case MULTIPLY: {
                int summ = 1;
                for (Expression<Integer> parameter : parameters) {
                    summ *= parameter.getValue(executionContext);
                }
                return summ;
            }
            case SUBTRACT: {
                return parameters[0].getValue(executionContext) - parameters[1].getValue(executionContext);
            }
            default: {
                throw new UnsupportedExpressionException(this);
            }
        }
    }
}
